import React, { useEffect, useRef, useState } from 'react';
import { Table, Button, Modal, Form, Input, Select, message, Row, Switch, Space } from 'antd';
import { groups } from '@/utils/data';
import { useHeight } from '@/utils/hooks/height';
import { colWidth } from '@/utils/tools';
import { updatePwdApi, getListApi, deletePersonApi, addPersonApi } from '@/request/personManage';
import { getListApi as getRoleListApi } from '@/request/role';
import { refreshApi } from '@/request/review';
import { useRouter } from 'next/router';
import PageTitle from '@/components/pageTitle';
import AuthWrapper from '@/components/authwrapper';
import MyModal from '@/components/modal';
import Icon from '@/components/layout/Icon';
import md5 from 'js-md5';
import styles from './index.module.css';

const PersonManage = () => {
  const [dialog, setDialog] = useState(false);
  const [form] = Form.useForm();
  const [pwdForm] = Form.useForm();
  const [dataSource, setDataSource] = useState([]);
  const [isEdit, setEdit] = useState<boolean>(false);
  const [confirmDialog, setConfirmDialog] = useState<boolean>(false); // 二次确认弹框
  const [pwdDialog, setPwdDialog] = useState<boolean>(false);
  const { height } = useHeight(250);
  const curRecord = useRef<any>({});
  const [roleList, setRoleList] = useState<any>([]);
  const router = useRouter();

  const handleGetRoleList = async () => {
    try {
      const res = await getRoleListApi();
      setRoleList(res);
    } catch (err) {
      console.log(err);
    }
  };

  const handleGetList = async (params = {}) => {
    try {
      const res: any = await getListApi(params);
      if (res) {
        setDataSource(res);
        return res;
      }
    } catch (err: any) {
      console.log(err.message);
    }
    return false;
  };

  const handleOk = async () => {
    const data = form.getFieldsValue();
    try {
      const res = await addPersonApi({ ...data, isEdit });
      if (res) {
        handleGetList();
        setDialog(false);
        form.resetFields();
      }
    } catch (err: any) {
      console.log(err.message);
    }
  };

  const handleShowConfirm = (record) => {
    curRecord.current = record;
    setConfirmDialog(true);
  };

  const handleDelete = async (record) => {
    const { _id } = record;
    try {
      const res = await deletePersonApi({ _id });
      if (res) {
        message.success('删除成功');
        handleGetList();
        setConfirmDialog(false);
      }
    } catch (err: any) {
      console.log(err.message);
    }
  };

  const handleEdit = async (record) => {
    setEdit(true);
    console.log(roleList);
    if (roleList.length === 0) {
      await handleGetRoleList();
    }
    const res = await getListApi({ _id: record._id });
    if (res) {
      setDialog(true);
      form.setFieldsValue({
        ...res[0],
        role: res[0].role?._id || undefined,
      });
    }
  };

  useEffect(() => {
    handleGetList();
  }, []);

  const handleUpdatePwd = (record) => {
    setPwdDialog(true);
    pwdForm.setFieldsValue({
      name: record.name,
      personId: record._id,
    });
  };

  const updatePwdOk = async () => {
    const data = await pwdForm.getFieldsValue();
    if (data.password !== data.passwordSure) {
      message.warning('两次密码不一致');
      return;
    }
    data.password = md5(data.password);
    data.passwordSure = md5(data.passwordSure);
    const res = await updatePwdApi(data);
    if (res) {
      message.success('修改成功');
      setPwdDialog(false);
      pwdForm.resetFields();
    }
  };

  const columns: any = [
    {
      title: '姓名',
      dataIndex: 'name',
      width: 80,
      align: 'left',
      showSorterTooltip: false,
      sorter: (a, b) => a.name.localeCompare(b.name),
    },
    {
      title: '分组',
      dataIndex: 'group',
      width: 160,
      showSorterTooltip: false,
      sorter: (a, b) => a.group.localeCompare(b.group),
      render(text) {
        const res = groups.filter((item) => item.value === text);
        if (res) {
          return <span>{res[0]?.label}</span>;
        }
        return <span>-</span>;
      },
    },
    {
      title: '角色',
      dataIndex: 'role',
      width: 100,
      align: 'left',
      showSorterTooltip: false,
      sorter: (a, b) => b.role._id - a.role._id,
      render(text) {
        return <span>{text?.roleName || '-'}</span>;
      },
    },
    {
      title: 'Review顺序',
      dataIndex: 'weight',
      width: 100,
      align: 'center',
      showSorterTooltip: false,
      sorter: (a, b) => b.weight - a.weight,
    },
    {
      title: '值班顺序',
      dataIndex: 'onDuty',
      width: 100,
      align: 'center',
      showSorterTooltip: false,
      sorter: (a, b) => b.onDuty - a.onDuty,
    },
    {
      title: '操作',
      dataIndex: 'operation',
      width: 100,
      render(text, record) {
        return (
          <Space>
            <span
              className="tableActionBtn"
              onClick={() => {
                handleEdit(record);
              }}
            >
              编辑
            </span>
            <span
              className="tableActionBtn"
              onClick={() => {
                handleShowConfirm(record);
              }}
            >
              删除
            </span>
            <AuthWrapper>
              <span
                className="tableActionBtn"
                onClick={() => {
                  handleUpdatePwd(record);
                }}
              >
                重置密码
              </span>
            </AuthWrapper>
          </Space>
        );
      },
    },
  ];

  // 刷新review
  const handleRefresh = async () => {
    const res = await refreshApi();
    if (res) {
      message.success('更新成功');
      router.push('/dashboard');
    }
  };

  return (
    <div className="person-manage">
      <PageTitle title="人员管理" />
      <Row justify="space-between">
        <div className={styles.title}>人员列表</div>
        <Space>
          <Button
            className="flex"
            type="primary"
            onClick={() => {
              refreshApi();
            }}
            style={{ marginBottom: '20px' }}
          >
            更新review顺序
          </Button>
          <Button
            className="flex"
            type="primary"
            icon={<Icon src="/images/add.png" width={16} height={16} style={{ marginRight: '4px' }} />}
            onClick={() => {
              setEdit(false);
              setDialog(true);
              if (roleList.length === 0) {
                handleGetRoleList();
              }
            }}
            style={{ marginBottom: '20px' }}
          >
            添加
          </Button>
        </Space>
      </Row>
      <Table columns={columns} dataSource={dataSource} scroll={{ x: colWidth(columns), y: height }} rowKey="name" pagination={false}></Table>
      {/* 编辑、新增人员 */}
      <MyModal
        width={600}
        title={isEdit ? '编辑人员信息' : '新增人员信息'}
        destroyOnClose
        open={dialog}
        onOk={() => {
          handleOk();
        }}
        onCancel={() => {
          setDialog(false);
          form.resetFields();
        }}
      >
        <Form labelCol={{ flex: '80px' }} wrapperCol={{ span: 14 }} form={form}>
          <Form.Item label="" name="_id" hidden>
            <Input placeholder="请输入姓名" />
          </Form.Item>
          <Form.Item label="姓名" name="name">
            <Input placeholder="请输入姓名" />
          </Form.Item>
          <Form.Item label="分组" name="group">
            <Select placeholder="请选择" options={groups} />
          </Form.Item>
          <Form.Item label="review顺序" name="weight">
            <Input placeholder="请输入" type="number"></Input>
          </Form.Item>
          <Form.Item label="值班顺序" name="onDuty">
            <Input placeholder="请输入" type="number"></Input>
          </Form.Item>
          {/* <Form.Item label="是否是组长" name="groupLeader" valuePropName="checked">
            <Switch />
          </Form.Item> */}
          <Form.Item label="角色" name="role">
            <Select placeholder="请选择" options={roleList} fieldNames={{ label: 'roleName', value: '_id' }} />
          </Form.Item>
        </Form>
      </MyModal>
      {/* 确认删除 */}
      <MyModal
        destroyOnClose
        title="提示"
        open={confirmDialog}
        width={600}
        onCancel={() => {
          setConfirmDialog(false);
          curRecord.current = {};
        }}
        onOk={() => {
          handleDelete(curRecord.current);
        }}
      >
        <div style={{ padding: '30px 0' }}>{`确认删除人员 “${curRecord.current.name as string}” 吗？`}</div>
      </MyModal>
      {/* 修改密码 */}
      <MyModal
        destroyOnClose
        title="重置密码"
        open={pwdDialog}
        width={600}
        onCancel={() => {
          setPwdDialog(false);
          pwdForm.resetFields();
        }}
        onOk={() => {
          updatePwdOk();
        }}
      >
        <Form labelCol={{ flex: '80px' }} wrapperCol={{ span: 14 }} form={pwdForm}>
          <Form.Item label="" name="personId" hidden>
            <Input />
          </Form.Item>
          <Form.Item label="姓名" name="name">
            <Input placeholder="请输入姓名" />
          </Form.Item>
          <Form.Item label="新密码" name="password">
            <Input placeholder="请输入" type="password"></Input>
          </Form.Item>
          <Form.Item label="确认密码" name="passwordSure">
            <Input placeholder="请输入" type="password"></Input>
          </Form.Item>
        </Form>
      </MyModal>
    </div>
  );
};

export default PersonManage;
